package com.daring.mysql2maxkb;

import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import java.io.StringReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlToTextConverter {
    public static String convertHtmlToText(String html) {
        // 使用正则表达式移除XML命名空间声明
        html = removeXmlNamespaceDeclarations(html);
        StringBuilder text = new StringBuilder();
        try {
            ParserDelegator parserDelegator = new ParserDelegator();
            HTMLEditorKit.ParserCallback callback = new HTMLEditorKit.ParserCallback() {
                @Override
                public void handleText(char[] data, int pos) {
                    text.append(new String(data));
                }

                // 忽略其他HTML标签
                // ...
            };
            parserDelegator.parse(new StringReader(html), callback, true);
        } catch (Exception e) {
            System.err.println("Error converting HTML to text: " + e.getMessage());
        }
        // 检查结果是否仅包含空白字符
        if (text.toString().trim().isEmpty()) {
            return null; // 返回null表示转换结果无效
        }
        return text.toString();
    }

    private static String removeXmlNamespaceDeclarations(String html) {
        Pattern pattern = Pattern.compile("\\<\\?xml:.*? />", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(html);
        StringBuffer cleanedHtml = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(cleanedHtml, "");
        }
        matcher.appendTail(cleanedHtml);
        return cleanedHtml.toString();
    }


    public static void main(String[] args) {
        String html = "<html><body><h1>Example</h1>Hello, <b>World!</b></body></html>";
        System.out.println(convertHtmlToText(html));
        html = "<html><o:OfficeDocumentSettings xmlns:o=\"urn:schemas-microsoft-com:office:office\"><o:AllowPNG/></o:OfficeDocumentSettings><body><h1>Example</h1>Hello, <b>World!</b></body></html>";
        System.out.println(convertHtmlToText(html));
    }
}
